$(function () {
	let millisecond = 1000 * 60 * 60 * 24, currentDate
	/**
	 * 渲染折线图
	 * @param {object} obj 其中 obj.xAxis.data, obj.yAxis.data 为 x, y 轴数据, 为必传数据
	 */
	function renderChart(obj) {
		var chartDom = document.getElementById(obj.id);
		var myChart = echarts.init(chartDom);
		var option;
		option = {
			color: ['#60db1d'],
			title: {
				text: obj.title + ' (单位: ' + obj.unit + ')' || '',
				textStyle: {
					fontSize: '16px',
					color: '#ccc'
				}
			},
			tooltip: {
				trigger: 'axis',
				textStyle: {
					color: '#333'
				}
			},
			legend: {
				y: 'bottom',
				textStyle: {
					color: '#ccc'
				}
			},
			toolbox: {
				show: true,
				feature: {
					dataZoom: {
						yAxisIndex: 'none'
					},
					dataView: {
						readOnly: false
					},
					magicType: {
						type: ['line', 'bar']
					},
					restore: {},
					saveAsImage: {}
				}
			},
			xAxis: {
				type: 'category',
				boundaryGap: false,
				data: obj.xAxis.data,
				axisLine: {
					lineStyle: {
						color: '#ccc',
						width: '2'
					}
				},
			},
			yAxis: [{
				type: 'value',
				axisLine: {
					lineStyle: {
						color: '#ccc',
						width: '2'
					}
				}
			}],
			series: [{
				name: obj.title || '',
				type: 'line',
				data: obj.yAxis.data,
				markLine: {
					data: [{
						type: 'average',
						name: 'Avg'
					}]
				}
			}]
		};
		option && myChart.setOption(option);
	}
	/**
	 * 创建长度为传递的参数的数组, 数组为 0~100 之间的随机数
	 * @param {number} num 控制数组的长度
	 * @returns {array}
	 */
	function randomArr(num) {
		var arr = []
		for (let i = 0; i < num; i++) {
			arr.push(Math.floor(Math.random() * 100))
		}
		return arr
	}
	/**
	 * 根据传递的参数设置渲染折线图的参数
	 * @param {string} typeId 判断其是 '温湿度' 还是 'SF6'
	 * @param {string} type 根据其值设置单位
	 * @returns {object}
	 */
	function getParam(typeId, type) {
		var obj = {
			id: type == 'temperature' ? 'main' : 'chart',
			startTime: new Date(),
			endTime: new Date(),
			pointId: 1,
			xAxis: {
				data: []
			},
			yAxis: {
				data: []
			}
		}
		switch (typeId) {
			case '温湿度':
				obj.title = type == 'temperature' ? '温度' : '湿度'
				obj.unit = type == 'temperature' ? '℃' : '%'
				break
			case 'SF6':
				obj.title = type == 'temperature' ? '压力' : '微水'
				obj.unit = type == 'temperature' ? 'bar(20℃)' : 'ppm(20℃)'
				break
		}
		return obj
	}
	/**
	 * ajax 请求
	 * @param {object} obj
	 */
	function ajax(obj) {
		obj = obj || {}
		/* $.ajax({
			url: '/Point/PointForDate',
			type: 'post',
			dataType: 'json',
			data: {
				pointId: searchKeyObj['pointid'],
				startTime: obj.startTime || new Date().format(),
				endTime: obj.endTime || new Date().format(),
				type: obj.type || 1,	//type: 1 小时 2 天  3 月 4年
				pointType: searchKeyObj['type']		//pointType: 1 温湿度传感器  2 sf6传感器  3 红外传感器
			},
			beforeSend: function (xhr) {
				xhr.setRequestHeader('SiteApp.Web', 'qDV0Dyovqz+76NoaeCXucw==')
			},
			success: (data) => {
				if (data.returnCode == 200) {
					$.each(data.data, (index, item) => {
						if (item != null && (index == 'temperature' || index == 'pressure') && obj.id == 'main') {
							if (obj.type == 1) obj.xAxis.data = item.xArr.map(item => new Date(item).format('HH:mm'))
							else obj.xAxis.data = item.xArr.map(item => new Date(item).format('MM-DD'))
							obj.yAxis.data = item.yArr
							renderChart(obj)
						} else if (item != null && (index == 'humidity' || index == 'moisture') && obj.id == 'chart'){
							if (obj.type == 1) obj.xAxis.data = item.xArr.map(item => new Date(item).format('HH:mm'))
							else obj.xAxis.data = item.xArr.map(item => new Date(item).format('MM-DD'))
							obj.yAxis.data = item.yArr
							renderChart(obj)
                        }
                    })
                }
            }
		}) */
		post({
			url: '/Point/PointForDate',
			data: {
				pointId: searchKeyObj['pointid'],
				startTime: obj.startTime || new Date().format(),
				endTime: obj.endTime || new Date().format(),
				type: obj.type || 1,	//type: 1 小时 2 天  3 月 4年
				pointType: searchKeyObj['type']		//pointType: 1 温湿度传感器  2 sf6传感器  3 红外传感器
			},
			success: (data) => {
				if (data != null) {
					$.each(data, (index, item) => {
						if (item != null && (index == 'temperature' || index == 'pressure') && obj.id == 'main') {
							if (obj.type == 1) obj.xAxis.data = item.xArr.map(item => new Date(item).format('HH:mm'))
							else obj.xAxis.data = item.xArr.map(item => new Date(item).format('MM-DD'))
							obj.yAxis.data = item.yArr
							renderChart(obj)
						} else if (item != null && (index == 'humidity' || index == 'moisture') && obj.id == 'chart') {
							if (obj.type == 1) obj.xAxis.data = item.xArr.map(item => new Date(item).format('HH:mm'))
							else obj.xAxis.data = item.xArr.map(item => new Date(item).format('MM-DD'))
							obj.yAxis.data = item.yArr
							renderChart(obj)
						}
					})
				}
			}
        })
	}
	function getNextMoth(date) {
		//获得当前月份0-11
		var currentMonth = date.getMonth();
		//获得当前年份4位年
		var currentYear = date.getFullYear();
		//下个月的第一天
		//年份为11代表,是本年的最后一月,所以不能加
		if (currentMonth == 11) {
			currentMonth = 0 //月份为下一年的第一个月份
			currentYear++; //年份加1
		}
		else {
			currentMonth++
		}
		return {
			currentYear,
			currentMonth
        }
    }
	/**
	 * 判断点击的按钮并渲染折线图, 并显示相对应的按钮
	 * @param {string} txt 根据该值判断获取点击的按钮
	 * @param {string} type 根据其值设置单位
	 */
	function render(txt, type) {
		let obj = getParam(typeId, type)
		switch (txt) {
			case 'day':
				obj.type = 1
				currentDate = new Date()
				obj.startTime = obj.endTime = new Date().format()
				ajax(obj)
				$('.' + obj.id + ' .timer').text(currentDate.getFullYear())
				$('.' + obj.id + ' .btn-group-data-group').hide().siblings('.btn-data').show()
				break
			case 'week':
				obj.type = 2
				var week = new Date().getDay() != 0 ? new Date().getDay() - 1 : 6
				currentDate = new Date(new Date().getTime() - week * millisecond)
				obj.startTime = currentDate.format()
				obj.endTime = new Date(currentDate.getTime() + 6 * millisecond).format()
				ajax(obj)
				let a = new Date(obj.startTime).getFullYear(),
					b = new Date(obj.endTime).getFullYear()
				a != b ? $('.' + obj.id + ' .timer').text(a + '- ' + b) : $('.' + obj.id + ' .timer').text(a)
				$('.' + obj.id + ' .btn-group-data-group').hide().siblings('.btn-week').show()
				break
			case 'month':
				obj.type = 3
				//获得当前月份0-11
				var currentMonth = new Date().getMonth()
				//获得当前年份4位年
				var currentYear = new Date().getFullYear()
				//求出本月第一天
				currentDate = new Date(currentYear, currentMonth, 1)
				obj.startTime = currentDate.format()
				//当为12月的时候年份需要加1
				//月份需要更新为0 也就是下一年的第一个月
				//否则只是月份增加,以便求的下一月的第一天
				if (currentMonth == 11) {
					currentYear++;
					currentMonth = 0;
				} else {
					currentMonth++;
				}
				//下月的第一天
				var nextMonthDayOne = new Date(currentYear, currentMonth, 1)
				//求出本月的最后一天
				obj.endTime = new Date(nextMonthDayOne.getTime() - millisecond).format()
				ajax(obj)
				$('.' + obj.id + ' .timer').text(currentDate.getFullYear())
				$('.' + obj.id + ' .btn-group-data-group').hide().siblings('.btn-month').show()
				break
			case 'year':
				obj.type = 4
				//获得当前年份4位年
				var currentYear = new Date().getFullYear()
				currentDate = new Date(currentYear, 0, 1)
				obj.startTime = currentDate.format()
				obj.endTime = new Date(currentYear, 11, 31).format()
				ajax(obj)
				$('.' + obj.id + ' .timer').text(currentDate.getFullYear())
				$('.' + obj.id + ' .btn-group-data-group').hide().siblings('.btn-year').show()
				break
			case 'propday':
				obj.type = 1
				currentDate = new Date(currentDate.getTime() - millisecond)
				obj.startTime = obj.endTime = currentDate.format()
				ajax(obj)
				$('.' + obj.id + ' .timer').text(currentDate.getFullYear())
				break
			case 'nextday':
				obj.type = 1
				currentDate = new Date(currentDate.getTime() + millisecond)
				obj.startTime = obj.endTime = currentDate.format()
				ajax(obj)
				$('.' + obj.id + ' .timer').text(currentDate.getFullYear())
				break
			case 'propweek':
				obj.type = 2
				currentDate = new Date(currentDate.getTime() - 7 * millisecond)
				obj.startTime = currentDate.format()
				obj.endTime = new Date(currentDate.getTime() + 6 * millisecond).format()
				ajax(obj)
				let c = new Date(obj.startTime).getFullYear(),
					d = new Date(obj.endTime).getFullYear()
				c != d ? $('.' + obj.id + ' .timer').text(c + ' - ' + d) : $('.' + obj.id + ' .timer').text(c)
				break
			case 'nextweek':
				obj.type = 2
				currentDate = new Date(currentDate.getTime() + 7 * millisecond)
				obj.startTime = currentDate.format()
				obj.endTime = new Date(currentDate.getTime() + 6 * millisecond).format()
				ajax(obj)
				let e = new Date(obj.startTime).getFullYear(),
					f = new Date(obj.endTime).getFullYear()
				e != f ? $('.' + obj.id + ' .timer').text(e + ' - ' + f) : $('.' + obj.id + ' .timer').text(e)
				break
			case 'propmonth':
				obj.type = 3
				//获得当前月份0-11
				var currentMonth = currentDate.getMonth();
				//获得当前年份4位年
				var currentYear = currentDate.getFullYear();
				var currentDay = new Date(currentYear, currentMonth, 1);
				//上个月的第一天
				//年份为0代表,是本年的第一月,所以不能减
				if (currentMonth == 0) {
					currentMonth = 11 //月份为上年的最后月份
					currentYear-- //年份减1
				}
				else {
					currentMonth--
				}
				currentDate = new Date(currentYear, currentMonth, 1)
				obj.startTime = currentDate.format()
				obj.endTime = new Date(currentDay.getTime() - millisecond).format()
				ajax(obj)
				$('.' + obj.id + ' .timer').text(currentDate.getFullYear())
				break
			case 'nextmonth':
				obj.type = 3
				var nextMonth1 = getNextMoth(currentDate)
				currentDate = new Date(nextMonth1.currentYear, nextMonth1.currentMonth, 1)
				obj.startTime = currentDate.format()
				var nextMonth2 = getNextMoth(currentDate)
				obj.endTime = new Date(new Date(nextMonth2.currentYear, nextMonth2.currentMonth, 1).getTime() - millisecond).format()
				ajax(obj)
				$('.' + obj.id + ' .timer').text(currentDate.getFullYear())
				break
			case 'propyear':
				obj.type = 4
				var currentYear = currentDate.getFullYear()
				currentYear--
				currentDate = new Date(currentYear, 0, 1)
				obj.startTime = currentDate.format()
				obj.endTime = new Date(currentYear, 11, 31).format()
				ajax(obj)
				$('.' + obj.id + ' .timer').text(currentDate.getFullYear())
				break
			case 'nextyear':
				obj.type = 4
				var currentYear = currentDate.getFullYear()
				currentYear++
				currentDate = new Date(currentYear, 0, 1)
				obj.startTime = currentDate.format()
				obj.endTime = new Date(currentYear, 11, 31).format()
				ajax(obj)
				$('.' + obj.id + ' .timer').text(currentDate.getFullYear())
				break
			default:
				break
		}
	}
	/**
	 * 设置页面中 id 为传递的参数的元素的内容为对应 url 参数的值
	 */
	setText('devType')
	setText('device')
	setText('grade')
	setText('devName')
	setText('position')
	/**
	 * 根据 url 中参数为 'devType' 的值渲染默认折线图
	 */
	let searchKeyObj = JSON.parse(getLocalStorage('searchKey'))
	let typeId = searchKeyObj['devType']
	render('day', typeId == '温湿度' ? 'temperature' : 'humidity')
	render('day', typeId == '温湿度' ? 'humidity' : 'temperature')
	/**
	 * 给所有的 button 注册事件
	 */
	$(document).on('click', '.btn', function () {
		var txt = $(this).data('text')
		var type = $(this).data('type')
		render(txt, type)
	})
})